<template>
  <div>
    <!-- 添加角色按钮 -->
    <el-button
      type="primary"
      @click="
        model = {};
        dialogFormVisible = true;
      "
      >添加角色</el-button
    >
    <!-- 表格 -->
    <Table :lists="list" :column="col">
      <template v-slot:expand="{ row }">
        <!-- 渲染权限 -->
        <el-row :gutter="20" v-for="(item, index) in row.children" :key="index">
          <!-- 一级权限 -->
          <el-col :span="3" class="cols-item">
            <el-tag closable @close="getdelTree(row.id, item.id)">
              {{ item.authName }}
            </el-tag>
          </el-col>
          <el-col :span="21">
            <!-- 二级 三级 权限 -->
            <div v-for="(it, index) in item.children" :key="index">
              <el-row :gutter="20" class="box">
                <el-col :span="4" class="cols-item">
                  <el-tag
                    closable
                    type="success"
                    @close="getdelTree(row.id, it.id)"
                  >
                    {{ it.authName }}
                  </el-tag>
                </el-col>
                <el-col :span="20" class="row-item">
                  <el-tag
                    type="warning"
                    closable
                    v-for="(i, index) in it.children"
                    :key="index"
                    @close="getdelTree(row.id, i.id)"
                  >
                    {{ i.authName }}
                  </el-tag>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </template>

      <template v-slot:action="{ row }">
        <el-button
          size="small"
          type="primary"
          @click="
            model = { ...row };
            dialogFormVisible = true;
          "
          >编辑</el-button
        >
        <el-button size="small" type="danger" @click="getdelRoles(row.id)"
          >删除</el-button
        >
        <el-button
          size="small"
          type="warning"
          @click="
            getTree(row);
            model = { ...row };
          "
          >分配权限</el-button
        >
      </template>
    </Table>
    <!-- 弹出框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="title"
      :close-on-click-modal="false"
    >
      <el-form :model="model" :rules="rules" label-width="120px" status-icon>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="model.roleName" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="model.roleDesc" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="getAddRoles">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配权限弹出框 -->
    <el-dialog
      v-model="TreeVisible"
      title="分配权限"
      :close-on-click-modal="false"
    >
      <!-- default-expand-all 默认打开 -->
      <el-tree
        ref="treeref"
        :data="tree"
        show-checkbox
        default-expand-all="true"
        :props="{ label: 'authName', children: 'children' }"
        node-key="id"
        :default-checked-keys="pidall"
      >
      </el-tree>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="TreeVisible = false">取消</el-button>
          <el-button type="primary" @click="AddTree">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import api from "@/http/roles.js";
import { reactive, onMounted, toRefs, computed, ref } from "vue";
import { ElMessageBox } from "element-plus";
export default {
  name: "roles",
  setup() {
    /**
     * 树形列表的ref
     */
    const treeref = ref();
    const state = reactive({
      /**
       * 列表存储
       */
      pidall: [],
      /**
       * tree 数据
       */
      tree: [],
      /**
       * tree 弹出框的显示隐藏
       */
      TreeVisible: false,
      /**
       * 数据模型
       */
      model: {},
      /**
       * 规则
       */
      rules: {
        roleName: [
          {
            required: true,
            message: "请输入角色名称",
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: "用户名的长度在2～10个字",
            trigger: "blur",
          },
        ],
        roleDesc: [
          {
            required: true,
            message: "请输入角色描述",
            trigger: "blur",
          },
        ],
      },
      /**
       * 弹出框的显示
       */
      dialogFormVisible: false,
      /**
       * 存储数据
       */
      list: [],
      /**
       * 表格配置项
       */
      col: [
        {
          type: "expand",
          slot: "expand",
        },
        {
          type: "index",
          label: "",
        },
        {
          prop: "roleName",
          label: "角色名称",
        },
        {
          prop: "roleDesc",
          label: "角色描述",
        },
        {
          label: "操作",
          slot: "action",
        },
      ],
    });
    /**
     * 删除Tree
     */
    let getdelTree = async (id, rids) => {
      const res = await api.delTree(id,rids);
      console.log(res,"删除tree");
      if(res.meta.status == 200){
        getList()
      }
    };
    /**
     * 更新 tree
     */
    let AddTree = async (row) => {
      console.log(treeref, "");
      const trees = treeref.value;

      let all = trees.getCheckedKeys(); //若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组
      let half = trees.getHalfCheckedKeys(); //若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点的 key 所组成的数组
      console.log(all, half, "..id");
      let str = [...all, ...half].join(",");
      console.log(state.model.id, "id");

      const res = await api.UpdataTree({ id: state.model.id, rids: str });
      if (res.meta.status == 200) {
        state.TreeVisible = false;
        getList();
      }
      console.log(res);
    };
    /**
     * 获取Tree数据
     */
    let getTree = async (role) => {
      state.TreeVisible = true;
      // console.log(role, "role");
      const res = await api.TreeList();
      if (res.meta.status == 200) {
        state.tree = res.data;
        
        function fn(role) {
          if (!role.children) {
            return state.pidall.push(role.id);
          }
          role.children.forEach((item) => {
            return fn(item);
          });
        }
        fn(role);
      }
      // console.log(res, "tree");
    };
    /**
     * 删除用户
     */
    let getdelRoles = (id) => {
      ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          console.log(id);
          const res = await api.delRoles(id);
          // console.log(res, "row");
          if (res.meta.status == 200) {
            getList();
          }
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消删除",
          });
        });
    };
    /**
     * 添加编辑
     */
    let getAddRoles = async () => {
      const res = await (state.model.id ? api.UpdataRoles : api.AddRoles)(
        state.model
      );

      if (res.meta.status == 200 || res.meta.status == 201) {
        state.dialogFormVisible = false;
        getList();
      }
    };
    /**
     * 获取数据
     */
    let getList = async () => {
      const res = await api.RolesList();
      console.log(res.data);
      if (res.meta.status == 200) {
        state.list = res.data;
        console.log(state.list, "权限");
      }
    };
    /**
     * 标题
     */
    let title = computed(() => {
      return state.model.id ? "编辑角色 " : "添加角色";
    });
    onMounted(() => {
      getList();
    });

    return {
      ...toRefs(state),
      getList, //获取数据
      title, //标题
      getAddRoles, //添加 编辑 角色
      getdelRoles, //删除角色
      getTree, //获取tree数据
      AddTree, //更新tree
      getdelTree, //删除tree
      treeref, //树形列表的ref
    };
  },
};
</script>

<style lang="scss" scoped>

.box {
  width: 900px;
}
.cols-item {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
  border: 1px solid rgb(142, 141, 141, 0.5);
}
.row-item {
  padding: 7px;
  border: 1px solid rgb(142, 141, 141, 0.5);
  flex-wrap: wrap;
  margin-top: 10px;
  .el-tag {
    margin-left: 5px;
  }
}
</style>